package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.constants.wemedia.WemediaContans;
import com.usian.common.kafka.NewsAutoScanConstants;
import com.usian.common.kafka.WmNewsMessageConstants;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends BaseServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url")
    private String fileServerUrl;

    @Autowired
    private WmMaterialMapper mMapper;
    @Autowired
    private WmNewsMaterialMapper nmMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //参数检查
        if (dto == null) return paramError;
        //分页条件查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) wrapper.eq(WmNews::getStatus, dto.getStatus());
        //频道精确查询
        if (dto.getChannelId() != null) wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) wrapper.like(WmNews::getTitle, dto.getKeyword());
        //查询当前登录用户的信息
        Integer user = WmThreadLocalUtils.getUser();
        if (user == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        wrapper.eq(WmNews::getUserId, user);
        //按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> newsPage = new Page<>(dto.page, dto.size);
        IPage<WmNews> page = page(newsPage, wrapper);

        //3.结果封装返回
        ResponseResult result = new PageResponseResult(dto.page, dto.size, (int) page.getTotal());
        result.setData(page.getRecords());
        result.setHost(fileServerUrl);
        return result;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto wmNews, Short isSubmit) {
        if (wmNews == null || StringUtils.isBlank(wmNews.getContent())) return paramError;
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNews, news);
        if (wmNews.getType().equals(WemediaContans.WM_NEWS_TYPE_AUTO)) news.setType(null);
        StringBuffer buffer = new StringBuffer();
        for (String image : wmNews.getImages()) {
            buffer.append(image.replace(fileServerUrl, "")).append(",");
        }
        news.setImages(buffer.toString().substring(0, buffer.toString().length() - 1));
        saveWmNews(news, isSubmit);

        String content = wmNews.getContent();
        JSONArray array = JSON.parseArray(content);
        List<String> materials = new ArrayList<>();//用来存放文章内容的中的所有图片路劲
        for (Object o : array) {
            JSONObject object = JSON.parseObject(o.toString());
            if (object.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String url = object.getString("value");
                materials.add(url.replace(fileServerUrl, ""));
            }
        }

        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            if (materials.size() != 0) saveRelativeInfoForContent(materials, news.getId());
            saveRelativeInfoForCover(wmNews, materials, news);
        }
        return null;
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_COVER_REFERENCE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        nmMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){

            if(wmNews.getArticleId()!=null){
                Map<String,Object> mesMap = new HashMap<>();
                mesMap.put("enable",dto.getEnable());
                mesMap.put("articleId",wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));
            }

            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease(){
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime,new Date()));
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return resultList;
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    public PageResponseResult findListAndPage(NewsAuthDto dto){
        //1.检查参数
        dto.checkParam();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        dto.setTitle("%"+dto.getTitle()+"%");

        //2.分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        return responseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
        if(wmNews!=null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //3.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }


    /**
     * @param wmNews    前端传过来的新闻对象
     * @param materials 内容中图片的集合
     * @param news      刚刚保存的文章对象
     */
    private void saveRelativeInfoForCover(WmNewsDto wmNews, List<String> materials, WmNews news) {
        List<String> images = wmNews.getImages();//前端传过来的封面图集合
        if (wmNews.getType().equals(WemediaContans.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() == 1 || materials.size() == 2) {
                images = Arrays.asList(materials.get(0));
                news.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
            } else if (materials.size() > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                news.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
            } else news.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            if (images != null && images.size() != 0) {
                news.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fileServerUrl, "")
                        .replace(" ", ""));
            }
            updateById(news);
        }
        if (images != null && images.size() != 0) {
            saveRelativeInfoForImage(images, news.getId());
        }
    }

    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer id) {
        List<String> image = images.stream().map(s -> s.replace(fileServerUrl, "")).collect(Collectors.toList());
        return saveRelativeInfo(image, id, WemediaContans.WM_COVER_REFERENCE);
    }

    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer id) {
        return saveRelativeInfo(materials, id, WemediaContans.WM_CONTENT_REFERENCE);
    }

    private ResponseResult saveRelativeInfo(List<String> materials, Integer id, Short wmContentReference) {
        List<WmMaterial> list = mMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser()));
        List<String> idList = new ArrayList<>();
        list.forEach(m -> idList.add(m.getId() + ""));
        nmMapper.saveRelationsByContent(idList, id, wmContentReference);
        return null;
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 自媒体文章发布
     * 添加修改方法
     * @param wmNews
     * @param isSubmit
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser());
        wmNews.setSubmitedTime(new Date());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId()==null){   //前台传来没ID就是添加,有ID就是修改
            save(wmNews);  //添加
        }else {
            //修改 先将关系表中和此新闻ID有关联的全部清空 再进行统一添加
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            nmMapper.delete(wrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews); //修改
        }
        //将添加或者修改的新闻id发送给监听者进行自送审核
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,wmNews.getId().toString());
    }

    /**
     * 提取图片信息
     *
     * @param list
     * @return
     */
    private List<String> ectractUrlInfo(List<Map> list) {
        List<String> materials = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                materials.add(imgUrl);
            }
        }
        return materials;
    }


    public static void main(String[] args) {
        String s1 = "1";
        String s2 = "1";
        System.out.println("s1 == s2 is:" + s1 == s2);
    }


}
